<?php


namespace app\admin\controller;


use app\common\exception\ParameterFailedException;
use app\common\model\MediaModel;
use app\common\service\Lang;
use app\common\service\Qiniu;
use app\Request;
use think\facade\Db;

class MediaController
{
    public function getMediaList()
    {
        $mediaList = (new MediaModel())->select();
        return retJson(Lang::GETDone, $mediaList->toArray());
    }

    /**
     * @param  Request  $request
     * @return \think\response\Json
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/8/17
     * @Time: 18:23
     */
    public function postImage(Request $request)
    {
        Db::startTrans();
        $deleteImagesSet  = [];
        $doneImagesUrlSet = [];
        try {
            $files = $request->file();
            validate(['image' => 'filesize:5242880|fileExt:jpg,jpeg,png,gif'])->check($files);
            foreach ($files as $file) {
                $savename          = 'storage/'.\think\facade\Filesystem::disk('public')->putFile('download',
                        $file);
                $deleteImagesSet[] = $savename;
                $encrypted_id      = $file->sha1();
                $oldMediaModel     = (new MediaModel())->where('encrypted_id', $encrypted_id)->find();
                if ($oldMediaModel) {
                    throw new ParameterFailedException([
                        'msg'  => '该图片已存在',
                        'data' => [
                            'exist_url' => $oldMediaModel->filename
                        ]
                    ]);
                }
                //5242880 B(字节) = 5 MB(兆字节)
                $mediaModel                   = new MediaModel();
                $mediaModel->filename         = $savename;
                $mediaModel->encrypted_id     = $encrypted_id;
                $mediaModel->type             = 'IMAGE';
                $mediaModel->storage_location = 'LOCAL';
                $mediaModel->save();
                $doneImagesUrlSet[] = $mediaModel->getAttr('filename');
            }

            Db::commit();
            return retJson(Lang::POSTDone, $doneImagesUrlSet);
        } catch (\Exception $e) {
            Db::rollback();
            foreach ($deleteImagesSet as $item) {
                if (is_file(app()->getRootPath().'public/'.$item)) {
                    unlink(app()->getRootPath().'public/'.$item);
                }
            }
            throw $e;
        }
    }

    public function deleteImage()
    {
        return retJson(Lang::DELETEDone);
    }

    public function putVideo()
    {
        return retJson(Lang::PUTDone);

    }

    public function deleteVideo()
    {
        return retJson(Lang::DELETEDone);
    }
}